package com.newworld.dmsapp2.activity.serviceapply;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.SysApplication;

public class SoundActivity extends Activity implements OnClickListener {

	public static final int SELECT_PIC_BY_TACK_PHOTO = 1; // 使用照相机拍照获取图片
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2; // 使用相册中的图片
	public static final String KEY_PHOTO_PATH = "photo_path"; // 从Intent获取图片路径的KEY
	private static final String TAG = "SelectPicActivity";
	// private LinearLayout dialogLayout;
	private TextView cancelBtn;
	private TextView takePhotoBtn;
	private String picPath; // 获取到的图片路径
	private Intent lastIntent;

	private boolean btn_vocie = true;
	private LinearLayout del_re;
	private int flag = 1;
	private View rcChat_popup;
	private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
			voice_rcd_hint_tooshort;
	private Handler mHandler = new Handler();
	private boolean isShosrt = false;
	private ImageView img1, sc_img1;
	private long startVoiceT, endVoiceT;
	private String voiceName;

	private ImageView volume;
	private Mp3Recorder recorder = new Mp3Recorder();

	protected int activityCloseEnterAnimation;

	protected int activityCloseExitAnimation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_sound);

		// 加上以后可以一键关闭所有界面 add by lxh
		SysApplication.getInstance().addActivity(this);
		TypedArray activityStyle = getTheme().obtainStyledAttributes(
				new int[] { android.R.attr.windowAnimationStyle });

		int windowAnimationStyleResId = activityStyle.getResourceId(0, 0);

		activityStyle.recycle();

		activityStyle = getTheme().obtainStyledAttributes(
				windowAnimationStyleResId,
				new int[] { android.R.attr.activityCloseEnterAnimation,
						android.R.attr.activityCloseExitAnimation });

		activityCloseEnterAnimation = activityStyle.getResourceId(0, 0);

		activityCloseExitAnimation = activityStyle.getResourceId(1, 0);

		activityStyle.recycle();
		initView();
	}

	/**
	 * 初始化加载View
	 */
	private void initView() {
		// dialogLayout = (LinearLayout) findViewById(R.id.dialog_layout);

		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		rcChat_popup = this.findViewById(R.id.rcChat_popup);
		voice_rcd_hint_rcding = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_rcding);
		voice_rcd_hint_loading = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_loading);
		voice_rcd_hint_tooshort = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_tooshort);
		img1 = (ImageView) this.findViewById(R.id.img1);
		sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
		// mSensor = new SoundMeter();
		volume = (ImageView) this.findViewById(R.id.volume);
		takePhotoBtn = (TextView) findViewById(R.id.btn_take_photo);
		takePhotoBtn.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				// 按下语音录制按钮时返回false执行父类OnTouch

				return false;

			}
		});
		cancelBtn = (TextView) findViewById(R.id.btn_cancel);
		cancelBtn.setOnClickListener(this);
		lastIntent = getIntent();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		default:
			finish();
			break;
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!Environment.getExternalStorageDirectory().exists()) {
			Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
			return false;
		}

		if (btn_vocie) {
			System.out.println("1");
			int[] location = new int[2];
			takePhotoBtn.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标

			int btn_rc_Y = location[1];
			int btn_rc_X = location[0];

			int[] del_location = new int[2];
			del_re.getLocationInWindow(del_location);
			int del_Y = del_location[1];
			int del_x = del_location[0];
			if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
				if (!Environment.getExternalStorageDirectory().exists()) {
					Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
					return false;
				}

				System.out.println("2");
				if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {// 判断手势按下的位置是否是语音录制按钮的范围内
					System.out.println("3");

					rcChat_popup.setVisibility(View.VISIBLE);
					voice_rcd_hint_loading.setVisibility(View.VISIBLE);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					voice_rcd_hint_tooshort.setVisibility(View.GONE);
					mHandler.postDelayed(new Runnable() {
						public void run() {
							if (!isShosrt) {
								voice_rcd_hint_loading.setVisibility(View.GONE);
								voice_rcd_hint_rcding
										.setVisibility(View.VISIBLE);
							}
						}
					}, 300);
					del_re.setVisibility(View.GONE);

					startVoiceT = System.currentTimeMillis();
					long time = System.currentTimeMillis();
					SimpleDateFormat format = new SimpleDateFormat(
							"yyyyMMddHHmmssS");
					Date d1 = new Date(time);
					String t1 = format.format(d1);
					// 重要的录音名字
					voiceName = t1 + ".mp3";
					// 重要的录音名字

					start(voiceName);
					flag = 2;
				}
			} else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {// 松开手势时执行录制完成

				mHandler.postDelayed(new Runnable() {
					public void run() {
						stop();
					}
				}, 500);

				if (event.getY() >= del_Y
						&& event.getY() <= del_Y + del_re.getHeight()
						&& event.getX() >= del_x
						&& event.getX() <= del_x + del_re.getWidth()) {
					rcChat_popup.setVisibility(View.GONE);
					// img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
					stop();
					flag = 1;
					String soundPath = Config.VOICE_PATH + voiceName;
					File file = new File(soundPath);
					if (file.exists()) {
						file.delete();
					}
				} else {

					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stop();
					// endVoiceT = SystemClock.currentThreadTimeMillis();
					endVoiceT = System.currentTimeMillis();
					flag = 1;

					// 重要的录音时间
					int time = (int) ((endVoiceT - startVoiceT) / 1000);
					// 重要的录音时间

					if (time < 1) {
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						mHandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);

						finish();
					}

					picPath = Config.VOICE_PATH + voiceName;
					lastIntent.putExtra(KEY_PHOTO_PATH, picPath);
					lastIntent.putExtra("voiceName", voiceName);
					lastIntent.putExtra("voiceTime",
							(int) ((endVoiceT - startVoiceT) / 1000));
					setResult(Activity.RESULT_OK, lastIntent);
					rcChat_popup.setVisibility(View.GONE);
					finish();

				}
				return false;
			}
			if (event.getY() < btn_rc_Y) {// 手势按下的位置不在语音录制按钮的范围内
				System.out.println("5");
				Animation mLitteAnimation = AnimationUtils.loadAnimation(this,
						R.anim.cancel_rc);
				Animation mBigAnimation = AnimationUtils.loadAnimation(this,
						R.anim.cancel_rc2);
				img1.setVisibility(View.GONE);
				del_re.setVisibility(View.VISIBLE);
				del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
				if (event.getY() >= del_Y
						&& event.getY() <= del_Y + del_re.getHeight()
						&& event.getX() >= del_x
						&& event.getX() <= del_x + del_re.getWidth()) {
					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
					sc_img1.startAnimation(mLitteAnimation);
					sc_img1.startAnimation(mBigAnimation);
				}
			} else {

				// img1.setVisibility(View.VISIBLE);
				del_re.setVisibility(View.GONE);
				del_re.setBackgroundResource(0);

			}
		} else {
			finish();
		}
		return super.onTouchEvent(event);
	}

	private void start(String name) {

		try {
			recorder.startRecording(name);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// mSensor.start(name);

		mHandler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private void stop() {
		mHandler.removeCallbacks(mSleepTask);
		mHandler.removeCallbacks(mPollTask);

		try {
			recorder.stopRecording();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// mSensor.stop();

		volume.setImageResource(R.drawable.amp1);
	}

	private static final int POLL_INTERVAL = 300;

	private Runnable mSleepTask = new Runnable() {
		public void run() {
			stop();
		}
	};
	private Runnable mPollTask = new Runnable() {
		public void run() {
			double amp = recorder.getAmplitude();
			updateDisplay(amp);
			mHandler.postDelayed(mPollTask, POLL_INTERVAL);

		}
	};

	private void updateDisplay(double signalEMA) {

		switch ((int) signalEMA) {
		case 0:
		case 1:
			volume.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			volume.setImageResource(R.drawable.amp2);

			break;
		case 4:
		case 5:
			volume.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			volume.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			volume.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			volume.setImageResource(R.drawable.amp6);
			break;
		default:
			volume.setImageResource(R.drawable.amp7);
			break;
		}
	}

	@Override
	public void finish() {

		Log.i(TAG, "finish");

		super.finish();

		overridePendingTransition(activityCloseEnterAnimation,
				activityCloseExitAnimation);

	}

	@Override
	protected void onDestroy() {
		Log.e("SoundActivity", "onDestroy");
		SysApplication.getInstance().rmActivity(this);
		super.onDestroy();
	}
}
